﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace LotroData
{
    internal static class LotroDataCacher
    {
        public static void SaveXmlCache(string name, LotroWorld world, XDocument doc, string savePath)
        {
            savePath += "/";

            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);

            doc.Save(BuildSaveCacheName(name,world,savePath));
        }

        public static XDocument LoadXmlCache(string name, LotroWorld world, string savePath)
        {
            savePath += "/";

            var dirInfo = new DirectoryInfo(savePath);

            var file = dirInfo.GetFiles(BuildSearchCacheName(name, world));

            return XDocument.Load(file[0].FullName);
        }

        public static bool IsValidXmlCache(string name, LotroWorld world, string savePath)
        {
            savePath += "/";

            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);

            var dirInfo = new DirectoryInfo(savePath);
            var file = dirInfo.GetFiles(BuildSearchCacheName(name, world));

            if (file.Count() > 0)
            {
                var fileName = file[0].Name;
                var cacheTime = DateTime.ParseExact(fileName.Substring(fileName.Length -16, 12), "yyyyMMddHHmm", null);

                return !(DateTime.Now.Subtract(cacheTime).Days >= 1);
            }
            else
                return false;
        }

        public static void DeleteXmlCache(string name, LotroWorld world, string savePath)
        {
            savePath += "/";

            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);

            var dirInfo = new DirectoryInfo(savePath);
            var file = dirInfo.GetFiles(BuildSearchCacheName(name, world));

            if (file.Count() > 0)
            {
                file[0].Delete();
            }
        }

        private static string BuildSearchCacheName(string name, LotroWorld world)
        {
            var builder = new StringBuilder();
            builder.Append(name);
            builder.Append("_");
            builder.Append(world.ToString());
            builder.Append("*");

            return builder.ToString();
        }

        private static string BuildSaveCacheName(string name, LotroWorld world, string path)
        {
            var builder = new StringBuilder();
            builder.Append(path);
            builder.Append(name);
            builder.Append("_");
            builder.Append(world.ToString());
            builder.Append("_");
            builder.Append(DateTime.Now.ToString("yyyyMMddHHmm"));
            builder.Append(".xml");

            return builder.ToString();
        }
    }
}
